<?php

/*
 * litchicms
 * Copyright (C) 2010-5-1 Author: tiefa(539247@qq.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
!defined('BRK') && exit("!");

/**
 *
 * @note 模板解析,返回生成的文件名
 * @param string $filename
 */
function template($filename) {
    //检查是否已有编译后的文件
    //如果没有强制更新就 直接返回
    $cachefilename = strtr(strtr($filename, '/', '_'), '\\', '_');
    if (file_exists(TPL_CACHE_DIR . $cachefilename) && !defined('IS_BUILD_TPL')) {
        return TPL_CACHE_DIR . $cachefilename;
    }
    !file_exists(TPL_DIR . $filename) && brk_log(0, TPL_DIR . $filename . " 模板不存在");
    $suffix = substr($filename, -4);
    if ($suffix != '.php')
        brk_log(0, TPL_DIR . $filename . " 模板无效");
    if (strpos(substr($filename, 0, -4), ".") !== FALSE)
        brk_log(0, TPL_DIR . $filename . " 模板无效");
    if (!is_dir(SYSTEM . 'cache'))
        if (!mkdir(SYSTEM . 'cache', 0777))
            exit("无法创建目录" . SYSTEM . 'cache');
    if (!is_dir(TPL_CACHE_DIR))
        if (!mkdir(TPL_CACHE_DIR, 0777))
            exit("无法创建目录" . TPL_CACHE_DIR);

    $string = template_merge($filename);

    $tpl_functions = array();
    //遍历模板处理函数文件夹
    if ($handle = opendir(SYSTEM . "include/template/")) {
        while (FALSE !== ($tpl_fun_file = readdir($handle))) {
            if ($tpl_fun_file != "." && $tpl_fun_file != ".." && preg_match("/^parse\.([a-z]+[a-z0-9_]*)\.php$/", $tpl_fun_file, $temparr)) {
                if (!function_exists('template_parse_' . $temparr[1])) {
                    include 'template/' . $tpl_fun_file;
                    $tpl_functions[] = 'template_parse_' . $temparr[1];
                }
            }
        }
        closedir($handle);
    } else {
        brk_log(0, "无法读取模板解析函数 - 请检查文件夹" . SYSTEM . "include/template/");
    }

    $template_parse_fun_array = array();
    $template_parse_fun_array[0] = "siteurl";
    $template_parse_fun_array[10] = "literal";
    $template_parse_fun_array[11] = "assign";
//    $template_parse_fun_array[15] = "dot2quote";
    $template_parse_fun_array[20] = "basevar";
    $template_parse_fun_array[30] = "cycle";
    $template_parse_fun_array[40] = "foreach";
    $template_parse_fun_array[50] = "if";
    $template_parse_fun_array[60] = 'quote';
    $template_parse_fun_array[70] = 'merge';

    ksort($template_parse_fun_array);
    foreach ($template_parse_fun_array as $v) {
        if (function_exists("template_parse_" . $v))
            $string = call_user_func("template_parse_" . $v, $string);
        else
            brk_log(0, "模板解析函数template_parse_" . $v . "不存在");
    }

    $string = preg_replace("/^\s+/is", "", $string);
    if (!empty($GLOBALS['BRK_SET']) && key_exists('removewrap', $GLOBALS['BRK_SET']) && $GLOBALS['BRK_SET']['removewrap'] == 'yes') {
        $string = preg_replace("/\>\s+\</is", "><", $string);
    }


    file_put_contents(TPL_CACHE_DIR . $cachefilename, $string);

    return TPL_CACHE_DIR . $cachefilename;
}

/**
 *
 * 递归组合模板文件,所有模板路径基于 常量TPL_DIR
 * @param $filename 文件名
 * @param $info_array 记录关系数组 防止递归嵌套
 * @return $string
 */
function template_merge($filename, $info_array=array()) {
    $temp = preg_replace("/[\/\\\.\s]/", "_", $filename);

    if (!empty($info_array[$temp])) {
        brk_log(0, $filename . '模板出现直接互相嵌套或者间接互相嵌套');
    } else {
        $info_array[$temp] = $temp;
    }
    !is_file(TPL_DIR . $filename) && brk_log(0, "未找到模板文件" . TPL_DIR . $filename);
    $string = file_get_contents(TPL_DIR . $filename);
    if (!preg_match("/^\<\?php\s+exit\(\"breakcms\"\);\s*\?\>/is", $string))
        brk_log(0, $filename . '模板文件必须以&lt;?php exit("breakcms");?&gt;作第一行');
    $string = preg_replace("/^\<\?php\s+exit\(\"breakcms\"\);\s*\?\>/is", '', $string);
    $string = preg_replace("/\{include\s*file\s*\=\s*[\"']?(.*?)[\"']?\s*\/?\}/ies", 'template_merge("\\1",$info_array)', $string);
//  $string = preg_replace("/\{include\s*file\s*\=\s*[\"']?(.*?)[\"']?\s*\}/ies", 'template_merge("\\1",$info_array)', $string);
    return $string;
}

/**
 * template_k2v 取得参数键值对
 * @param 参数字符串
 * @return 键值对数组
 */
function template_k2v($argstring) {

    $argstring = preg_replace(array("/\['/", "/']/"), array("_[danyinhao_", "_danyinhao]_"), trim($argstring));

    $argstring = preg_replace(array("/\s+/", "/['\"]/", "/\s*\=\s*/"), array(" ", "", "="), $argstring);

    $argstring = preg_replace(array("/_\[danyinhao_/", "/_danyinhao]_/"), array("['", "']"), $argstring);

    // $argstring  =  form="$arr" item="info" index="key" isahw
    $argsarr = explode(" ", $argstring);

    $temparr = array();
    foreach ($argsarr as $v) {
        $kv = explode("=", $v);
        $temparr[$kv[0]] = (array_key_exists(1, $kv)) ? $kv[1] : TRUE;
    }
    return $temparr;
}

/**
 * template_arr2patt 取得参数键值对
 * @param 参数字符串
 * @return 键值对数组
 */
function template_arr2patt(&$array) {
    foreach ($array as &$value) {
        $value = "/" . preg_quote($value, "/") . "/";
    }
    unset($value);
}

/**
 * template_var_call_fun 对变量使用函数的情况
 * @param  $v
 * @return $v
 */
function template_var_call_fun($v) {
    $varr = explode("|", preg_replace("/\\\\\|/", "_suxian_", $v));
    $tempstring = '';
    if (count($varr) == 1) {
        $tempstring.="$v";
    } else {
        $count = count($varr);
        $thisvar = "$varr[0]";
        for ($i = 1; $i < $count; $i++) {
            $varr[$i] = preg_replace(array("/\\\:/", "/\\\"/"), array("_mao_hao_", "_shuang_yinhao_"), $varr[$i]);
            $varr[$i] = explode(":", $varr[$i]);
            foreach ($varr[$i] as &$value) {
                $value = preg_replace(array("/_mao_hao_/", "/_shuang_yinhao_/", "/_suxian_/"), array(":", "\"", "|"), $value);
            }
            unset($value);
            $thisvartemp = "" . array_shift($varr[$i]) . "(";
            if (count($varr[$i]) == 0) {
                $thisvartemp.=$thisvar . ")";
            } else {
                $temps2 = implode(",", $varr[$i]);
                if (preg_match_all("(,this)", $temps2, $matchtemp)) {
                    $temps2 = preg_replace("/" . $matchtemp[0][0] . "/i", "," . $thisvar, $temps2);
                }
                if (preg_match_all("(this,)", $temps2, $matchtemp)) {
                    $temps2 = preg_replace("/" . $matchtemp[0][0] . "/i", $thisvar . ",", $temps2);
                }
                if (preg_match_all("(this)", $temps2, $matchtemp)) {
                    $temps2 = preg_replace("/" . $matchtemp[0][0] . "/i", $thisvar, $temps2);
                }
                $thisvartemp.=$temps2 . ")";
            }
            $thisvar = $thisvartemp;
        }
        $tempstring.=$thisvar . ";";
    }
    return $tempstring;
}
?>
